#include "led.h"

long lastMsg = 0;
char msg[50];
int value = 0;

const char* ssid = "Mi10";
const char* password = "13960379768czy";
const char* mqtt_server = "192.168.20.180";

//设备详情
String deviceId = "1111aaaa";
String deviceType = "板载灯";
String location = "客厅";

String clientId = "8266:" + deviceType + ":" + deviceId;

//控制灯相关
int stream_flag = 0;
int ledTimeDelay = 200;
int is_led_on = 0;


WiFiClient espClient;
PubSubClient client(espClient);
Ticker myTicker;
extern const char* mqtt_server;

//控制led状态
void controlLed(String msg)
{
  resolveJsonStringOfControlLed(msg);
  Serial.println(String(is_led_on)+ " " +String(stream_flag)+ " " + String(ledTimeDelay));
  controlOnOffLed(is_led_on);
}
//控制亮灭
void controlOnOffLed(int is_led_on)
{
  if(is_led_on){
    digitalWrite(LED_BUILTIN,0);
  }
  if(!is_led_on){
    digitalWrite(LED_BUILTIN,1);
  }  
}
//解析控制led的Json
void resolveJsonStringOfControlLed(String msg)
{
  String deviceStr;
  const size_t capacity = JSON_OBJECT_SIZE(4) + 70;
  DynamicJsonDocument doc(capacity);
  deserializeJson(doc, msg);
  deviceStr = doc["deviceId"].as<String>();
  if(deviceStr != deviceId)
  {
    return;
  }
  is_led_on    =  doc["isOn"].as<int>();
  stream_flag  =  doc["isStreamLedOn"].as<int>();
  ledTimeDelay =  doc["speed"].as<int>();
}
//控制交替闪烁
void streamLedInLoop()
{ 
  if(stream_flag==1){
      digitalWrite(LED_BUILTIN,LOW);
      delay(ledTimeDelay);
      digitalWrite(LED_BUILTIN,HIGH);
      delay(ledTimeDelay);
  }
}
//连接mqtt
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    
    if (client.connect(clientId.c_str(),"OFFLINE",1,false,deviceId.c_str())) {
      Serial.println("connected");
      //发送注册消息
      sendRegisterMsg();
      //订阅消息主题 mqtt_topic_001
      subscribeTopic();
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//获取注册信息的Json并转化为String
String getRegisterJsonString()
{
    String registerStr;
    StaticJsonDocument<200> doc;
    doc["deviceId"] = deviceId;
    doc["deviceType"] = deviceType;
    doc["online"] = "1";
    doc["location"] = location;
    serializeJson(doc, registerStr);
    return registerStr;
}
//订阅主题
void subscribeTopic(){
      client.subscribe("mqtt_topic_001");
      client.subscribe("controlLed");
}
//发送注册消息的msg
void sendRegisterMsg()
{
    String registerStr = getRegisterJsonString();
    Serial.println("Register:" + registerStr);
    client.publish("register_device",registerStr.c_str()) ;
}
//回调函数
void callback(char* topic, byte* payload, unsigned int length) {
  //接收到消息  这边就可以进行不同的主题判断进入不同的分支函数
  String strTopic = String(topic);
  String msgStr = getMsgStringByPayload(payload,length);
  Serial.println("Arrived||Topic:"+strTopic + "  Msg:" + msgStr);
  //判断主题
  if(strTopic == "controlLed")
  {
    controlLed(msgStr);
  }
}
//根据payload转化消息String
String getMsgStringByPayload(byte* payload,int length)
{
  String msgStr;
  for (int i = 0; i < length; i++) {
    msgStr +=(char)payload[i];
  }
  return msgStr;
}
//连接wifi
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//定时任务
void tickerHandle()
{
  Serial.println(deviceId);
  client.publish("Heart",deviceId.c_str());
}
